<?php

/**
 * visa.php
 *
 * Author: netman
 * DateTime:  2023/10/16 10:37
 */
class Service_Api_Visa extends Contract_Api_Product
{
    use Trait_Api_Visa;
    use Trait_Api_Common;

    /**
     * 类型ID
     */
    const TYPE_ID = 8;
    /**
     * @var Service_Api_Fenxiao
     */
    private $fenxiao_service = null;

    public function __construct()
    {
        $this->fenxiao_service = new Service_Api_Fenxiao();
    }

    /**
     * 产品搜索
     * @param  array  $params
     * @return array
     * User: netman
     * Date: 2023/9/11 17:47
     */
    function search(array $params = array()): array
    {
        $mid = $params['mid'];
        $kind = $params['area'];
        $sort_type = $params['sort_type'];
        $visatype = $params['visatype'];
        $p = $params['page'];
        $keyword = $params['keyword'];
        $city_id = $params['city_id'];
        $pagesize = $params['pagesize'] ? $params['pagesize'] : 10;
        $builder = DB::select(
            'visa.id','visa.aid','visa.title','visa.handleday','visa.price','visa.litpic','visa.cityid',
            'visa.bookcount','visa.satisfyscore','visa.recommendnum','visa.visatype','visa.needinterview','visa.refund_restriction','visa.attrlist','visa.iconlist'
        )
            ->from('visa')
            ->join('allorderlist', 'left')
            ->on('visa.id', '=', 'allorderlist.aid')
            ->on('allorderlist.typeid', '=', self::TYPE_ID)
            ->where('visa.ishidden', '=', 0);
        //区域
        if ($kind && $kind != 'all') {
            $kind_id = DB::select()->from('visa_area')->where('pinyin','=',$kind)->execute()->get('id');
            $builder->and_where(DB::expr(" AND (areaid={$kind_id} OR nationid={$kind_id}) "));
        }
        if ( ! empty($city_id)) {
            $builder->and_where('visa.cityid', '=', $city_id);
        }
        if ( ! empty($visatype)) {
            $builder->and_where('visa.visatype', '=', $visatype);
        }
        if ( ! empty($keyword)) {
            $builder->and_where('visa.title', 'like', '%'.$keyword.'%');
        }
        //排序
        $orderBy = "";
        if ( ! empty($sort_type)) {
            switch ($sort_type) {
                case 1://价格升序
                    $builder->order_by('visa.price', 'asc');
                    break;
                case 2://价格降序
                    $builder->order_by('visa.price', 'desc');
                    break;
                case 3://销量降序
                    $builder->order_by('visa.bookcount', 'desc');
                    break;
                case 4://推荐
                    $builder->order_by('visa.recommendnum', 'desc');
                    break;
            }
        }
        $builder->order_by(DB::expr("IFNULL(sline_allorderlist.displayorder,9999) Asc"));
        $offset = ($p - 1) * $pagesize;
        $total = $builder->execute()->count();
        $list = $builder->offset($offset)->limit($pagesize)->execute()->as_array();

        $list = $this->format_visa($list, $mid);

        $out = array(
            'total' => $total,
            'list' => $list,
            'status' => true
        );
        return $out;
    }

    /**
     * 产品详情
     * @param  array  $params
     * @return array
     * @throws Kohana_Exception
     * User: netman
     * Date: 2023/9/11 16:39
     */
    function info(array $params = array()): array
    {
        $product_id = $params['product_id'];
        $mid        = $params['mid'];
        $info       = DB::select()->from('visa')->where('id', '=', $product_id)->execute()->current();
        if (!$info) {
            throw new Exception("未找到签证信息");
        }
        $info['commentnum']   = Model_Comment::get_comment_num($info['id'], self::TYPE_ID);
        $info['satisfyscore'] = Model_Comment::get_score($info['id'], self::TYPE_ID, $info['satisfyscore'],
            $info['commentnum']);//满意度
        $info['sellnum']      = Model_Member_Order::get_sell_num($info['id'], self::TYPE_ID) + (int)$info['bookcount'];
        if ($info['attachment']) {
            $info['attachment'] = unserialize($info['attachment']);
        }
        if ($info['visatype']) {
            $visa_type = DB::select('kindname')->from('visa_kind')->where('id', '=',
                $info['visatype'])->execute()->get('kindname');
        } else {
            $visa_type = '';
        }
        $info['visa_type'] = $visa_type;
        $info['litpic']    = $this->img_url($info['litpic'],750,750);

        $info['extend_info'] = Model_Visa::visa_extend($info['id']);
        foreach ($info['extend_info'] as $k=>&$v) {
            if($v['name']=='签证附件' && count($v['attachment'])<1){
                unset($info['extend_info'][$k]);
                continue;
            }
            $v['content'] = $this->content_add_domain($v['content']);
        }
        sort($info['extend_info']);
        $info['cityname'] = DB::select()->from('visa_city')->where('id', '=', $info['cityid'])->execute()->get('kindname');

        foreach ($info['attachment']['path'] as $k => $path) {
            $info['attachment']['path'][$k] = $this->img_url($path);
        }
        $materials = Model_Visa_Material::get_list(1);
        foreach ($materials as $k => &$ma) {
            $content = Model_Visa_Material_Content::get_content($info['id'], $ma['pinyin']);
            if ($content) {
                $ma['content'] = $this->content_add_domain($content);
            } else {
                unset($materials[$k]);
            }
        }
        sort($materials);
        $info['materials'] = $materials;
        $pay_name             = array(
            '1' => '全款支付',
            '2' => '定金支付',
            '3' => '二次确认支付'
        );
        $info['paytype_name'] = $pay_name[$info['paytype']];
        // 获取产品编号
        $info['serial_number'] = St_Product::product_series($product_id, self::TYPE_ID);
        //分销赚取的金额
        if (St_Functions::is_normal_app_install('mobiledistribution')) {
            $info['profit'] = $this->fenxiao_service->get_estimate_profit(self::TYPE_ID, $mid, $info['id'],
                $info['price']);
        }
        // 积分抵现配置
        $jifenprice_info          = Model_Jifen_Price::get_used_jifentprice($info['jifentprice_id'], self::TYPE_ID);
        $info['jifentprice_info'] = $this->filter_data(array(
            'isopen',
            'id',
            'toplimit',
            'jifentprice'
        ),
            $jifenprice_info);
        // 预定送积分
        $jifenbook_info         = Model_Jifen::get_used_jifenbook($info['jifenbook_id'], self::TYPE_ID);
        $info['jifenbook_info'] = $this->filter_data(array(
            'isopen',
            'value',
            'rewardway'
        ), $jifenbook_info);
        //积分评论
        $jifencomment_info         = Model_Jifen::get_used_jifencomment(self::TYPE_ID);
        $info['jifencomment_info'] = $this->filter_data(array(
            'isopen',
            'value',
            'rewardway'
        ), $jifencomment_info);
        // 更加ID查询可用的优惠券
        if (St_Functions::is_normal_app_install('coupon')) {
            $coupon_list = Model_Coupon::xcx_get_product_coupon_list($info['id'], self::TYPE_ID, $mid);
            $coupons     = [];
            foreach ($coupon_list as $coupon) {
                $coupons[] = $this->filter_data(array(
                    'id',
                    'name'
                ), $coupon);
            }
            $info['coupon_list'] = $coupons;
        }
        //供应商
        if ($info['supplierlist']) {
            $info['suppliers'] = DB::select('suppliername', 'id')->from('supplier')->where('id', '=', $info['supplierlist'])->execute()->current();
        }
        //
        $nation              = DB::select('pid', 'kindname')->from('visa_area')->where('id', '=', $info['nationid'])->execute()->current();
        $nation_name         = DB::select('kindname')->from('visa_area')->where('id', '=', $nation['pid'])->execute()->get('kindname');
        $info['nation']      = $nation;
        $info['nation_name'] = $nation_name;
        $info['suppliers']   = DB::select()->from('supplier')->where('id', '=', $info['supplierlist'])->execute()->current();
        unset($info['webid'], $info['aid'], $info['keyword'], $info['description'], $info['tagword']);
        unset($info['themelist'], $info['templet'], $info['seotitle'], $info['areaid'], $info['nationid']);
        return $info;
    }

    /**
     * 产品查询条件
     * @return array
     * User: netman
     * Date: 2023/9/11 17:48
     */
    function query_condition(): array
    {
        $result = array(
            'sort' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量最高'),
                array('id' => 4, 'name' => '人气推荐')
            ),
            'attr' => array()
        );
        // 签证类型
        $filterAttr = DB::select('id', 'kindname')->from('visa_kind')->where('isopen', '=',
            1)->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')->execute()->as_array();
        $result['attr']['visa_type']['list'] = $filterAttr;
        $result['attr']['visa_type']['type_name'] = '签证类型';

        // 签发城市
        $city = DB::select()->from('visa_city')->where("isopen=1")->order_by('displayorder',
            'asc')->execute()->as_array();
        $result['attr']['visa_city']['list'] = $city;
        $result['attr']['visa_city']['type_name'] = '签发城市';

        // 签证区域
        $area = $this->get_area_child(0);
        foreach ($area as &$v) {
            $v['child'] = $this->get_area_child($v['id']);
        }
        $result['area'] = $area;
        return $result;
    }

    /**
     * 创建订单
     * @param  array  $params
     * @return array
     * User: netman
     * Date: 2023/9/13 16:24
     */
    function create_order(array $params = array()): array
    {
        //联系人
        $linkman = $params['linkman'];
        //预订时间
        $usedate = $params['use_date'];
        //手机号
        $linktel = $params['linktel'];
        //电子邮箱
        $linkemail = $params['linkemail'];
        //备注信息
        $remark = $params['remark'];
        //产品id
        $product_id = $params['product_id'];
        //预订数量
        $dingnum = $params['ding_num'];
        //订单来源 1PC,2WAP,3小程序,4平台添加
        $source = $params['source'];
        //会员id
        $member_id = $params['mid'];
        //会员信息
        $member_info = $params['member_info'];
        //地址id
        $address_id = $params['address_id'];
        if ( ! Model_Member_Address::check_address_id($member_id, $address_id) && $address_id) {
            throw new Exception('收货地址有误请重新选择');
        }
        //红包id
        $envelope_member_id = (int)$params['envelope_member_id'];//红包id

        //二次验证
        $info = Model_Visa::visa_detail_id($product_id);

        //积分抵现.
        $need_jifen = $params['need_jifen'];
        $jifentprice = 0;
        $use_jifen = 0;
        if ($need_jifen) {
            $jifentprice = Model_Jifen_Price::calculate_jifentprice($info['jifentprice_id'], self::TYPE_ID, $need_jifen, $member_info);
            $use_jifen = empty($jifentprice) ? 0 : 1;
            $need_jifen = empty($jifentprice) ? 0 : $need_jifen;
        }
        $addtime = time();
        if ($info['auto_close_time']) {
            $date = explode(':', $info['auto_close_time']);
            $hour = bcmul($date[0], 3600);
            $minute = bcmul($date[1], 60);
            $auto_close_time = $addtime + $hour + $minute;
        } else {
            $auto_close_time = $addtime + 1200;
        }
        //积分评论
        $jifencomment_info = Model_Jifen::get_used_jifencomment(self::TYPE_ID);
        $jifencomment = empty($jifencomment_info) ? 0 : $jifencomment_info['value'];
        //合并生成订单
        $ordersn = Product::get_ordersn(self::TYPE_ID);
        $arr = array(
            'ordersn' => $ordersn,
            'webid' => 0,
            'auto_close_time' => $auto_close_time,
            'typeid' => self::TYPE_ID,
            'productautoid' => $product_id,
            'productaid' => $info['aid'],
            'productname' => $info['title'],
            'litpic' => $info['litpic'],
            'price' => $info['price'],
            'childprice' => $info['childprice'],
            'jifentprice' => $jifentprice,
            'jifenbook' => $info['jifenbook_id'],
            'jifencomment' => $jifencomment,
            'paytype' => $info['paytype'],
            'dingjin' => $info['dingjin'],
            'usedate' => $usedate,
            'departdate' => $info['departdate'],
            'addtime' => $addtime,
            'memberid' => $member_id,
            'dingnum' => $dingnum,
            'childnum' => 0,
            'oldprice' => 0,
            'oldnum' => 0,
            'linkman' => $linkman,
            'linktel' => $linktel,
            'linkemail' => $linkemail,
            'linkidcard' => '',
            'suitid' => 0,
            'remark' => $remark,
            'status' => $info['status'] ?: 0,
            'usejifen' => $use_jifen,
            'needjifen' => $need_jifen,
            'refund_restriction' => $info['refund_restriction'],//退改条件
            'source' => $source,
            'receiver_address_id' => $address_id,
            'need_confirm' => $info['need_confirm'],
        );

        //优惠券
        $coupon_id = Arr::get($params, 'coupon_id', '');
        if ($coupon_id) {
            $coupon_check = Model_Api_V2_Coupon::order_use_coupon_check($coupon_id, $member_id, $arr);
        }

        //添加订单,跳转支付
        $out = Model_Api_V2_Order::add_order($arr, 'Model_Visa', $params);
        if ($out) {
            $order = Model_Member_Order::order_info($ordersn);

            // 优惠券
            if (!empty($coupon_check)) {
                Model_Coupon::add_coupon_order($coupon_check['cid'], $order['ordersn'], $coupon_check['order_total_price'], $coupon_check, $coupon_id);
            }

            //添加红包抵扣
            if (St_Functions::is_normal_app_install('red_envelope') && $envelope_member_id) {
                Model_Order_Envelope::order_use_envelope($envelope_member_id, $order['ordersn'], self::TYPE_ID,
                    $order['memberid']);
            }

            //订单结算信息表数据更新
            Model_Member_Order_Compute::update($order['ordersn']);

            // 订单创建完成事件
            Hook::trigger('order_created', $order);

            // 返回订单信息
            $filter_keys = array('id', 'orderid', 'ordersn', 'paytype', 'typeid', 'status');
            return $this->filter_data($filter_keys, $order);
        } else {
            throw new Exception($out['msg']);
        }
    }


}